<?php
namespace Common\Controller;
use Think\Controller;
require_once(APP_PATH.'/Common/Api/Wechat.php');
class CommonController extends Controller {
	protected $config;
	protected $wechat;
	public function _initialize(){
		$this ->wechat();
	}
    protected function wechat(){
    	$this -> getConfig();
    	$wechat = new \WeChat();
    	$appid = $this->config['appid'];
    	$appsecret = $this ->config['appsecret'];
    	$wechat ->setAppId($appid);
    	$wechat ->setAppSecret($appsecret);
    	$access_token = $this ->config['access_token'];
    	$time = time();
    	$access_token_time = $this -> config['access_token_time'];
    	if($time - $access_token_time>=7200){
    		$access_token = $wechat ->gettoken();
    		M('Config') ->where(array('key'=>'access_token'))->setField('value',$access_token);
    		M('Config') ->where(array('key'=>'access_token_time'))->setField('value',time());
    	}
    	$wechat ->setToken($access_token);
    	$this ->wechat = $wechat;
    }
    protected function getConfig(){
    	$arr = M('Config')->select();
    	foreach ($arr as $k=>$v){
    		$config[$v['key']] = $v['value'];
    	}
    	$this ->config = $config;
    }
    protected function getCurl($url){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

        //3、连接并得到结果
        $rs=curl_exec($ch);
        //4、关闭cURL资源，并且释放系统资源
        curl_close($ch);
        return json_decode($rs,true);

    }
    protected function postCurl($url,$data=''){
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_POST,true);
            if($data){
                curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
            }
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

            //3、连接并得到结果
            $rs=curl_exec($ch);
            echo $rs;
            //4、关闭cURL资源，并且释放系统资源
            curl_close($ch);
            return json_decode($rs,true);

        }
}